package com.leo.contentcenter.service.content;

import com.leo.contentcenter.dao.content.ShareMapper;
import com.leo.contentcenter.domain.dto.content.ShareDTO;
import com.leo.contentcenter.domain.dto.user.UserDTO;
import com.leo.contentcenter.domain.entity.content.Share;
import com.leo.contentcenter.feignclient.UserCenterFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * @author leo
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShareService {
    private final ShareMapper shareMapper;
    private final UserCenterFeignClient userCenterFeignClient;

    public ShareDTO findById(Integer id) {
        // 获取分享详情
        Share share = this.shareMapper.selectByPrimaryKey(id);
        // 发布人id
        Integer userId = share.getUserId();

        //强调：
        //了解stream ---> JDK 8
        //lambda表达式
        //functional --> 函数式变成



        // 怎么调用用户微服务的/user/{userId}
        //用HTTP GET方法去请求，并且返回一个对象

        //1. 代码不可读
        //2. 负载的url难以维护：
        //3. 难以进行相应需求的变化，变化很没有幸福感
        //4. 编程体验不统一
        UserDTO userDTO = this.userCenterFeignClient.findById(userId);

        ShareDTO shareDTO = new ShareDTO();

        //消息的装配
        BeanUtils.copyProperties(share,shareDTO);
        shareDTO.setWxNickname(userDTO.getWxNickname());

        return shareDTO;
    }

    public static void main(String[] args){
        RestTemplate restTemplate = new RestTemplate();
        //用HTTP GET方法去请求，并且返回一个对象
        String forObject = restTemplate.getForObject("http://localhost:8080/users/1",
                String.class);
        //RestTemplate还支持占位符
        String forObject2 = restTemplate.getForObject("http://localhost:8080/users/{id}}",
                String.class,1);
        //用HTTP GET方法去请求，并且返回一个对象,和getForObject之外，还能拿到getStatusCode()响应码。即http的状态码
        ResponseEntity<String> forEntity = restTemplate.getForEntity(
                "http://localhost:8080/users/1",
                String.class
        );
        System.out.println(forEntity.getBody());

        //200 OK
        //500
        //502 bad gateway
        System.out.println(forEntity.getStatusCode());
    }
}
